/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.core;

import com.inspur.edp.lcm.metadata.core.dao.MdRecentUseDao;
import com.inspur.edp.lcm.metadata.core.domain.GspMdRecentUse;
import com.inspur.edp.lcm.metadata.inner.api.WsService;
import com.inspur.edp.lcm.metadata.inner.api.utils.WsUtils;
import io.iec.edp.caf.boot.context.CAFContext;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 用户最近打开元数据操作服务类
 */
@Slf4j
public class MdRecentUseService {
    private MdRecentUseDao mdRecentUseDao;
    private static final int MAXCOUNT = 20;
    /**
     * 记录用户打开元数据操作信息
     *
     * @param mdId 元数据编号
     * @param mdPath 元数据全路径
     * @param appId  关键应用id
     * @param sourceType 元数据来源
     * @param mdType 元数据类型
     */
    public void saveMdRecentUse(String mdId,  String mdPath, String appId, String sourceType, String mdType) {

        String wsId = null;
        WsService wsService = WsUtils.getWsService();
        if (Objects.nonNull(wsService)) {
            wsId = wsService.getActiveWorkSpaceId();
        }
        String userId = CAFContext.current.getUserId();
        LocalDateTime time = LocalDateTime.now();
        GspMdRecentUse recentUse = getMdRecentUseDao().findOneByUserIdAndWsIdAndAppCodeAndSourceTypeAndMdId(userId,wsId,appId,sourceType,mdId);
        if (Objects.nonNull(recentUse)) {
            recentUse.setWeight(recentUse.getWeight() + 1).setLastUsedTime(time).setMdType(mdType);
            getMdRecentUseDao().save(recentUse);
            return;
        }

        // 一个用户在一个关键应用下允许记录最大条数为20，超过20则覆盖时间最早的
        List<GspMdRecentUse> gspMdRecentUseList = getMdRecentUseDao().findByUserIdAndWsIdAndAppCode(userId,wsId,appId);
        if (!CollectionUtils.isEmpty(gspMdRecentUseList) && gspMdRecentUseList.size() >= MAXCOUNT) {
            List<GspMdRecentUse> gspMdRecentUseSortedList = gspMdRecentUseList.stream().sorted(Comparator.comparing(GspMdRecentUse::getLastUsedTime)).collect(Collectors.toList());
            GspMdRecentUse lastRecord = gspMdRecentUseSortedList.get(0);
            lastRecord.setMdPath(mdPath).setMdId(mdId).setAppCode(appId).setLastUsedTime(time).setSourceType(sourceType).setWeight(1).setMdType(mdType);
            getMdRecentUseDao().save(lastRecord);
            return;
        }
        GspMdRecentUse gspMdRecentUse = new GspMdRecentUse();
        gspMdRecentUse.setId(UUID.randomUUID().toString())
                .setUserId(userId)
                .setWsId(wsId)
                .setAppCode(appId)
                .setMdId(mdId)
                .setSourceType(sourceType)
                .setMdPath(mdPath)
                .setMdType(mdType)
                .setLastUsedTime(time)
                .setWeight(1);
        getMdRecentUseDao().save(gspMdRecentUse);
    }

    /**
     * 获取用户最近在关键应用中使用过的元数据列表
     *
     * @param appId 关键应用id
     * @return
     */
    public List<GspMdRecentUse> getRecnetMdUseList(String appId,String sourceType) {
        if (Objects.isNull(appId)) {
            return null;
        }
        String wsId = null;
        WsService wsService = WsUtils.getWsService();
        if (Objects.nonNull(wsService)) {
            wsId = wsService.getActiveWorkSpaceId();
        }
        List<GspMdRecentUse> mdRecentUseList;
        if(StringUtils.hasText(sourceType)){
            // 零代码只查询数据库中的元数据记录
            mdRecentUseList = getMdRecentUseDao().findByUserIdAndWsIdAndAppCodeAndSourceType(CAFContext.current.getUserId(),wsId,appId,sourceType);
        }else {
            mdRecentUseList = getMdRecentUseDao().findByUserIdAndWsIdAndAppCode(CAFContext.current.getUserId(),wsId,appId);
        }
        if (CollectionUtils.isEmpty(mdRecentUseList)) {
            return null;
        }

        return mdRecentUseList.stream().sorted(Comparator.comparing(GspMdRecentUse::getLastUsedTime).reversed()).limit(MAXCOUNT).collect(Collectors.toList());
    }

    /**
     * 批量删除
     * @param list
     */
    public void deleteInBatch(List<GspMdRecentUse> list) {
        getMdRecentUseDao().deleteInBatch(list);
    }


    private MdRecentUseDao getMdRecentUseDao() {
        if (Objects.isNull(mdRecentUseDao)) {
            mdRecentUseDao = SpringBeanUtils.getBean(MdRecentUseDao.class);
        }
        return mdRecentUseDao;
    }

}
